<template>
    <div class="red-index" v-if="dThirdAuth" id="redIndex" v-cloak>
        <div class="red-nav">
            <div class="nav-left">
                <a @click="toHaoKanHaoWan()" href="javascript:;"><img class="nav-img"
                                                                      :src="staticImageUrl('images/red_nav.png')"
                                                                      alt=""/></a>
            </div>
            <div class="nav-right">
                <a @click="toHaoKanHaoWan()" href="javascript:;" class="scramble-red">抢红包</a>
            </div>
        </div>
        <div class="big-red">
            <div class="top">
                <span class="user-header-wrap"><img class="user-header" :data-userId="pageMsg.userId"
                                                    :src="pageMsg.photo" alt=""/></span>
                <span class="dialog-box">
					<span class="triangle-left"></span>
				<span class="dialog-box-text">{{pageMsg.receiverSpeak}}</span>
				</span>
                <span class="person-number">
					<span class="user-headers" v-for="(value,key) in pageMsg.grabbingPhotos" :key="key" v-if="key < 3">
						<img class="user-header-list" :src="value" alt=""/>
					</span>
				<span class="number-statistics">
						等{{pageMsg.grabbingPeopleNum}}人正在抢红包
					</span>
				</span>
            </div>
            <div class="red-content-wrap">
                <img v-if="pageMsg.showPacketEnd" class="red-end-poke" :src="staticImageUrl('images/red_end.png')"
                     alt=""/>
                <h2 v-if="pageMsg.packetTitle" class="greeting">{{pageMsg.packetTitle}}</h2>
                <div class="red-shadow-wrap">
                    <div class="red-shadow"></div>
                    <img class="shop-logo" :src="pageMsg.storeLogo" alt=""/>
                </div>
                <p class="shop-title" :data-storeId="pageMsg.storeId">{{pageMsg.storeName}}</p>
                <div>
                    <!--进度条,助力-->
                    <div class="red-progress-bar">
						<span class="rate" ref="rate"
                              :style="{'width': !pageMsg.showPacketEnd ? Math.round(pageMsg.curHelperNum/pageMsg.needHelperNum * 100) + '%' : '100%'}">
							<img class="packet-location" :src="staticImageUrl('images/process_redpacket.png')" alt=""/>
						</span>
                    </div>
                    <span class='help-btn' :class="{'btn-gray':!pageMsg.canHelpBtnClick}"
                          @click="helpHim(pageMsg.showPacketEnd,pageMsg.canHelpBtnClick)">
						<span>帮TA加速</span>
						<span class="red-poke-wrap" v-if="pageMsg.showHelpedSign">
							<img class="red-poke" :src="staticImageUrl('images/red_help_border.png')" alt=""/>
							<p class="red-increase success-increase">解锁成功</p>
						</span>
					</span>
                    <a v-if="!pageMsg.curUserHasPacket" @click="createRedPage" class="need-btn" href="javascript:;">
                        我也要红包
                    </a>
                    <!--有自己的红包团，且这不是自己的红包团-->
                    <router-link class="need-btn"
                                 :to="{path:`/welfare/help/packet/${pageMsg.myPacketInfo.receiverId}/detail`}"
                                 v-else-if="pageMsg.curUserHasPacket && pageMsg.myPacketInfo && pageMsg.myPacketInfo.receiverId !== pageMsg.receiverId">
                        返回我的红包
                    </router-link>
                    <!--有自己的红包团，且这是自己的红包团,出现弹窗-->
                    <a v-else-if="pageMsg.curUserHasPacket && pageMsg.myPacketInfo && pageMsg.myPacketInfo.receiverId === pageMsg.receiverId"
                       @click="showRedAlert" class="need-btn" href="javascript:;">
                        查看我的红包
                    </a>
                </div>
            </div>
        </div>
        <div class="arc-wrap">
            <span class="red-arc"></span>
        </div>
        <div class="title-wrap">
			<span class="left">
				<img :src="staticImageUrl('images/red_title_side.png')" alt=""/>
			</span>
            <span class="red-title">手气榜</span>
            <span class="right">
				<img :src="staticImageUrl('images/red_title_side.png')" alt=""/>
			</span>
        </div>
        <marquee-list-swiper :swiperOptionProps="swiperOption" :rankListProps="rankList"
                             v-if="Object.keys(swiperOption).length > 0"></marquee-list-swiper>
        <!--底部悬浮的下载app的东西-->
        <div class="height50px"></div>
        <bottom-down></bottom-down>
        <!--弹出框-->
        <get-red-alert
                ref="getRedAlert"
                v-if="isShowAlert && Object.keys(getPageData).length > 0"
                :getRedProps="getPageData"
                @showRedAlert="showRedAlert"
                @sharePage="sharePage"
                @openRedPage="openRedPage"></get-red-alert>
        <v-alert v-if="alerts.box" :alert-msg="alerts.msg"></v-alert>
        <v-bord v-if="alerts.box" :activity-name="activityName"></v-bord>
        <!--微信分享-->
        <wx-share-body v-if="Object.assign(share)" :shareBody="share"></wx-share-body>
        <!--分享的蒙版-->
        <v-share v-if="shareBordShow" @clickFn="shareBordShow = false"></v-share>
    </div>
</template>

<script>

    // import vAlert from './components/Alert';
    // import bord from './components/BlackBord';
    // import WxShareBody from '../../wx/WxShareBody';
    // import toast from './components/Toast';
    import xurl from '../../x/xurl'
    import XUser from '../../x/XUser'

    export default {
        name: 'redIndex',
        data() {
            return {
                pageMsg: {},
                rankList: [],
                helpResult: {},
                share: {},
                dThirdAuth: false,
                getPageData: {},
                isShowAlert: false,
                shareBordShow: false,
                'activityName': 'red',
                'alerts': {
                    box: false,
                },
                swiperOption: {},
            }
        },
        created() {
            //获取页面信息
            if (XUser.toLogin()) {
                return
            }
            this.getPageMsg();
        },
        mounted() {
            let that = this;
            document.title = 'red Page';
            this.init();
        },
        methods: {
            init() {
                //获取排行榜
                this.getRank();
            },
            helpHim(showPacketEnd, canHelpBtnClick) {
                let result;
                if (canHelpBtnClick) {
                    let url = this.NW_API_vue + "/welfare/help/packet/" + this.$route.params.receiverId + "/help/click"
                    xurl.getLoading(url).then((data) => {
                        if (data.success) {
                            //弹出框
                            this.pageMsg.curHelperNum++;
                            result = parseInt(1 / this.pageMsg.needHelperNum * 1000) / 10;//保留一位小数字
                            this.helpResult = {packetType: 1, helpResult: result, time: 1};

                            this.alerts.msg = this.helpResult;
                            this.alerts.box = true;
                            //刷新页面两个数据
                            this.getPageMsg();
                            this.$root.$emit('toast', {msg: '加速成功'});
                        } else if (data.errMsg) {
                            this.$root.$emit('toast', {msg: data.errMsg})
                            this.getPageMsg();
                        } else {
                            this.$root.$emit('toast', {msg: '未知错误'})
                        }
                    });
                } else if (showPacketEnd) {//结束不能点击
                    this.$root.$emit('toast', {msg: "红包团已结束，感谢帮忙！"});
                } else if (this.pageMsg.showHelpedSign) {
                    this.$root.$emit('toast', {msg: '只能帮助加速1次'});
                } else {
                    this.$root.$emit('toast', {msg: '未知错误'});
                }
            },
            /*一定是已经开了才能看到自己的红包详情*/
            getPageDataDeal(obj) {
                /*增长红包随时可以领取*/
                let temp = {};
                let noHelp = !obj.myPacketInfo || (obj.myPacketInfo && !obj.myPacketInfo.packetHelpers) || (obj.myPacketInfo && obj.myPacketInfo.packetHelpers && obj.myPacketInfo.packetHelpers.length === 0)
                let hasHelp = obj.myPacketInfo && obj.myPacketInfo.packetHelpers && obj.myPacketInfo.packetHelpers.length > 0;
                if (noHelp) {
                    /*没有人帮助力的时候只显示邀*/
                    temp.showGetMoneyBtn = false;
                    temp.showGetBtn = false;
                    temp.showShareBtn = true;
                } else if (hasHelp && obj.myPacketInfo && !obj.myPacketInfo.waitInvitedNum === 0 && obj.myPacketInfo.canReceiveAmount > 0) {
                    /*有人助力、待邀约人数为零，且可领取金额不为零的时候只显示领*/
                    temp.showGetMoneyBtn = false;
                    temp.showGetBtn = true;
                    temp.showShareBtn = false;
                } else if (hasHelp && obj.myPacketInfo && obj.myPacketInfo.waitInvitedNum > 0 && !obj.myPacketInfo.completeReceived) {
                    /*有人帮助力、待邀约人数不为零，且红包未领取的时候只显示邀*/
                    temp.showGetMoneyBtn = false;
                    temp.showGetBtn = false;
                    temp.showShareBtn = true;
                } else if (hasHelp && obj.myPacketInfo && obj.myPacketInfo.completeReceived) {
                    /*有人帮助力且已经领取完的时候只显示提现*/
                    temp.showGetMoneyBtn = true;
                    temp.showGetBtn = false;
                    temp.showShareBtn = false;
                }
                temp.title = obj.packetTitle;
                temp.hasSelfPackage = obj.curUserHasPacket;
                temp.myPacketInfo = obj.myPacketInfo;//查看自己红包团的模型
                temp.redTypeState = 2;
                if (obj.myPacketInfo) {
                    temp.getMoney = obj.myPacketInfo.receivedAmount;
                }
                temp.rule = ['邀好友解锁红包', '领红包', '进APP提现'];
                this.getPageData = Object.assign({}, this.getPageData, temp);
                let hasNotOpenHelp = window.localStorage.getItem('hasNotOpenHelp') ? JSON.parse(window.localStorage.getItem('hasNotOpenHelp')) : true;
                if (hasNotOpenHelp && this.pageMsg.myPacketInfo && this.pageMsg.myPacketInfo.receiverId === this.pageMsg.receiverId) {
                    this.showRedAlert();
                    window.localStorage.setItem('hasNotOpenHelp', JSON.stringify(false));
                }
            },
            showRedAlert(booleanMsg = true) {
                if (!this.userId) {
                    this.$router.push('/to/login');
                    return
                }
                this.isShowAlert = booleanMsg;
                if (booleanMsg) {
                    this.$store.state.loadingImg = true;
                }
                setTimeout(() => {
                    if (this.$refs.getRedAlert) {
                        this.$refs.getRedAlert.redShow = true;
                    }
                }, 20)
            },
            createRedPage() {
                if (!this.userId) {
                    this.$router.push('/to/login');
                    return
                }
                /*先创建红包团，然后跳转到我的红包团*/
                let url = `${this.NW_API_vue}/welfare/packet/${this.pageMsg.welpacketId}/receiver/create`;
                this.putLoading(url).then((data) => {
                    if (data.success) {
                        window.localStorage.setItem('hasNotOpenHelp', JSON.stringify(true));
                        this.$router.push({path: `/welfare/help/packet/${data.result}/detail`});
                    } else if (data.errMsg) {
                        this.$root.$emit('toast', {msg: data.errMsg})
                    } else {
                        this.$root.$emit('toast', {msg: '创建红包团失败'});
                    }
                })
            },
            openRedPage() {
                if (!this.userId) {
                    this.$router.push('/to/login');
                    return
                }
                let url = `${this.NW_API_vue}/welfare/packet/${this.pageMsg.welpacketId}/receive`;
                this.putLoading(url).then((data) => {
                    if (data.success) {
                        let temp = {};
                        temp.getMoney = Number(data.result) + Number(this.getPageData.myPacketInfo.receivedAmount);
                        this.$refs.getRedAlert.redShow = false;
                        this.$refs.getRedAlert.isHideRed = true;
                        temp.hasSelfPackage = true;
                        this.getPageMsg();
                        this.getPageData = Object.assign({}, this.getPageData, temp);
                    } else if (data.errMsg) {
                        this.$root.$emit('toast', {msg: data.errMsg})
                    } else {
                        this.$root.$emit('toast', {msg: '查看红包团失败'});
                    }
                })
            },
            sharePage() {
                this.isShowAlert = false;
                this.shareBordShow = true;
            },
            closeAlert() {
                this.alerts.box = false;
                // //重新刷新页面的数据
                // this.getPageMsg();
            },
            callback() {
                console.log("callback")
            },
            getPageMsg() {
                let that = this;
                let url = `${this.NW_API_vue}/welfare/help/packet/${this.$route.params.receiverId}/detail`;
                xurl.get(url).then((data) => {
                    if (data.success) {
                        that.dThirdAuth = this.$store.state.isThirdLogin;
                        this.pageMsg = Object.assign({}, this.pageMsg, data.result);
                        this.getPageDataDeal(data.result);
                        //修改页面标题
                        // document.title = this.pageMsg.name + "喊你抢现金红包！！";
                        document.title = this.pageMsg.packetTitle;
                        //分享
                        this.share = data.result.shareBodyModel;
                    } else if (data.errMsg) {
                        this.$root.$emit('toast', {msg: data.errMsg});
                    } else {
                        this.$root.$emit('toast', {msg: '未知错误'});
                    }
                })
            },
            getRank() {
                let url = `${this.NW_API_vue}/welfare/packet/receiver/rank`;
                xurl.getLoading(url).then((data) => {
                    if (data.success) {
                        this.rankList = data.list.slice(0, 5);
                        let length = this.rankList.length;
                        this.swiperOption = {
                            pagination: {
                                el: '.swiper-pagination',
                            },
                            direction: 'vertical',
                            loop: true,
                            observer: true,
                            observeParents: true,
                            autoplay: 3000,
                            loopedSlides: length,
                            slidesPerGroup: 1,
                            slidesPerView: length > 2 ? 3 : length,
                            lazy: {
                                loadPrevNext: true,
                            },
                        }
                    } else if (data.errMsg) {
                        this.$root.$emit('toast', {msg: data.errMsg});
                    } else {
                        this.$root.$emit('toast', {msg: '未知错误'});
                    }
                })
            },
        },
        watch: {
            '$route': function () {
                window.location.reload();
            }
        },
        components: {
            'v-alert': () => import('./components/Alert'),
            'v-bord': () => import('./components/BlackBord'),
            'wx-share-body': () => import('../../components/wx/WxShareBody'),
            'bottom-down': () => import('./components/BottomDown'),
            'get-red-alert': () => import('./components/GetRedAlert'),
            'marquee-list-swiper': () => import('../../components/commonComponents/swiperComponent/SwiperMarquee'),
            "v-share": () => import("../../components/commonComponents/share/Share"),
        }
    }
</script>

<style scoped="scoped" lang="scss">
    /*@import url($css_root + 'css/red/red.css');*/
    @import url($css_root + 'css/swiper.min.css');
    @import url($css_root +'/css/red/red.css');
</style>
